<?php

namespace app\api\server;

use app\common\model\User as ModelUser;
use app\common\model\UserGroup;
use think\Controller;
use think\Db;
use think\Exception;

/**
 * 用户逻辑
 */
class User extends Controller
{

    /**
     * 绑定用户
     *
     */
    public static function binding_relationship($params)
    {

        extract($params);
        Db::startTrans();
        try {
            $user = ModelUser::get($uid);
            $pUser = ModelUser::get(['qr_code' => $qr_code]);
            if (!$pUser) {
                exception('邀请人不存在');
            }
            $pUser->setInc('first_num', 1);
            self::upgrade($pUser);
            if ($pUser->pid) {
                $tUser = ModelUser::get($pUser->pid);
                if ($tUser) {
                    $tUser->setInc('two_num', 1);
                    self::upgrade($tUser);
                }
            }

            //绑定关系
            $user->paren_ids =  trim($pUser->id . ',' . $pUser['paren_ids'], ',');
            $user->pid =  $pUser->id;
            $user->tid =  $pUser->pid;
            $user->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return true;
    }

    //检测用户是否满足升级条件
    public static function upgrade($user)
    {
        $group_id = $user->group_id;
        $level = $group_id + 1;
        //下一级升级条件
        $group = UserGroup::get($level);

        switch ($level) {

            case 3:
                if ($user->first_num >= $group->first_num && $user->two_num >= $group->two_num) {
                    $user->setInc('group_id', 1);
                }
                break;
            case 4:
                //团长人数
                $count = ModelUser::where("find_in_set({$user->id},paren_ids)")->where('group_id', '>', 2)->count();
                if ($count + 1 >= $group->team_num) {
                    $user->setInc('group_id', 1);
                }
                break;
        }
        return false;
    }

    //查询下级所有平级用户
    static function diguis($uid, $group_id)
    {
        $ids = [];
        $users = ModelUser::where('pid', $uid)->field('id,group_id')->select();
        if ($users) {
            foreach ($users as $k => $v) {
                if ($v['group_id'] >= $group_id) {
                    array_push($ids, $v['group_id']);
                } else {
                    self::diguis($v, $group_id);
                }
            }
        }
        return $ids;
    }

    //查询下级所有用户
    static function recursion($uid, &$arr)
    {

        $users = ModelUser::where('pid', $uid)->column('id');
        if ($users) {
            foreach ($users as $k => $v) {
                if ($v['group_id'] < $users['group_id']) {
                    array_push($arr, $v['id']);
                    self::recursion($v['id'], $arr);
                }
            }
        }
    }
}
